import { Book } from '../model/Book.js'
import { Op } from 'sequelize'
const fn_list = async (ctx, next) => {
  const keyword = ctx.request.query.keyword
  let where = {}
  if (keyword) {
    where = {
      [Op.or]: [
        { bookname: { [Op.like]: `%${keyword}%` } },
        { author: { [Op.like]: `%${keyword}%` } },
        { descriptions: { [Op.like]: `%${keyword}%` } }
      ]
    }
  }
  const books = await Book.findAll({ where })
  ctx.body = {
    code: 200,
    msg: 'ok',
    data: books
  }
}
const fn_getById = async (ctx, next) => {
  const id = ctx.request.params.id
  const book = await Book.findByPk(id)
  ctx.body = {
    code: 200,
    msg: 'ok',
    data: book
  }
}
const fn_add = async (ctx, next) => {
  const book = ctx.request.body
  await Book.create(book)
  ctx.body = {
    code: 200,
    msg: 'ok',
    data: null
  }
}
const fn_updata = async (ctx, next) => {
  const book = ctx.request.body
  const id = ctx.request.params.id
  await Book.update(book, {
    where: {
      id: id
    }
  })
  ctx.body = {
    code: 200,
    msg: 'ok',
    data: null
  }

}
const fn_delete = async (ctx, next) => {
  const id = ctx.request.params.id
  await Book.destroy({
    where: {
      id: id
    }
  })
  ctx.body = {
    code: 200,
    msg: 'ok',
    data: null
  }
}

export default [
  {
    mathod: 'get',
    url: '/book',
    fn: fn_list
  },
  {
    mathod: 'get',
    url: '/book/:id',
    fn: fn_getById
  },
  {
    mathod: 'post',
    url: '/book',
    fn: fn_add
  },
  {
    mathod: 'put',
    url: '/book/:id',
    fn: fn_updata
  },
  {
    mathod: 'delete',
    url: '/book/:id',
    fn: fn_delete
  }
]